﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models;
using KPIS.GERP.Models.ICM;
using System.Data.Entity;
using System.Collections.Generic;
using KPIS.GERP.Models.Class;
using UrlHelper = System.Web.Http.Routing.UrlHelper;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class RequestParcelController : Controller
    {

        #region RequestParcel

        public ActionResult Index()
        {
            int EmpId = KPIS.GERP.WEB.GIMS.Class.GimsMembership.CurrentEmpId;
            var service = new RequestParcelService.RequestParcelServiceClient();
            return View(service.SelectRequestParcel(new Models.ICM.RequestParcel { RequestBy = EmpId, RecordStatus = "!D" }, new[] { "Jobsite", "Project", "Employee" }));
        }

        public ActionResult Create()
        {
            RequestParcel model = new RequestParcel()
                { 
                    CreatedWhen = DateTime.Today, 
                    IcmReqCode = CodeGenerate.GetNextCode(CodeGenerate.TransectionType.RequestParcel, ""),
                    RequestBy = KPIS.GERP.WEB.GIMS.Class.GimsMembership.CurrentEmpId
                };
            //model.CreatedWhen = ;

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(RequestParcel model)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var JobsiteSeq = service.GetJobsite(Class.GimsMembership.CurrentEmpId);

            model.JobSiteId = Convert.ToInt32(JobsiteSeq[1]);

            if (model.CreatedWhen <= model.WantedDate)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        model.IcmReqCode = CodeGenerate.GetNextCode(CodeGenerate.TransectionType.RequestParcel, "");
                        int id = service.Insert(model, Class.GimsMembership.CurrentEmpId);
                        return RedirectToAction("Details", new { id = id });
                    }
                    View(model);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
            else
            {

                ViewBag.Message = "* วันที่ต้องการพัสดุ ต้องไม่น้อยกว่าวันที่ทำรายการ";

            }

            return View();
        }

        public ActionResult Edit(int id)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var item = service.SelectRequestParcel(new Models.ICM.RequestParcel { ReqParcelId = id, RecordStatus = "!D" }, new[] { "WarehousePermit.Warehouse", "Project" }).FirstOrDefault();
            ViewBag.State = "Edit";

            if (item == null)
            {
                return HttpNotFound();
            }
            return View(item);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(RequestParcel model)
        {
            if (model.CreatedWhen <= model.WantedDate)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        var service = new RequestParcelService.RequestParcelServiceClient();
                        var JobsiteSeq = service.GetJobsite(Class.GimsMembership.CurrentEmpId);
                        model.JobSiteId = Convert.ToInt32(JobsiteSeq[1]);
                        service.Update(model, Class.GimsMembership.CurrentEmpId);

                        return RedirectToAction("Details", new { id = model.ReqParcelId });
                    }
                    return Edit(model.ReqParcelId);
                }
                catch
                {
                    return Edit(model.ReqParcelId);
                }

            }
            else
            {
                ViewBag.Message = "* วันที่ต้องการพัสดุ ต้องไม่น้อยกว่าวันที่ทำรายการ";
            }

            return View();
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new RequestParcelService.RequestParcelServiceClient();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index");
            }
            catch
            {
                return Index();
            }
        }

        public ActionResult DeleteAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new RequestParcelService.RequestParcelServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        #endregion


        #region RequestParcelDtl

        public ActionResult Details(int id, bool? nolayout = false)
        {
            ViewBag.RequestId = id;
            ViewBag.NoLayout = nolayout;
            var service = new RequestParcelService.RequestParcelServiceClient();
            var model = service.SelectRequestParcelDtl(new Models.ICM.RequestParcelDtl { ReqId = id, RecordStatus = "!D" }, null);

            return View(model);
        }

        public ActionResult CreateDetails(int id)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var item = service.SelectRequestParcel(new Models.ICM.RequestParcel { ReqParcelId = id, RecordStatus = "!D" }, new[] { "WarehousePermit" }).FirstOrDefault();

            ViewBag.ReqId = id;
            ViewBag.Project = item.ProjectId;
            ViewBag.WhId = item.WarehousePermit.WhId;

            return View(new RequestParcelDtl());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateDetails(RequestParcelDtl model, string ddlParcelList, string hdReqId, string hdItemName, string ddlParcelType)
        {
            if (ModelState.IsValid)
            {
                var service = new RequestParcelService.RequestParcelServiceClient();
                var JobsiteSeq = service.GetJobsite(Class.GimsMembership.CurrentEmpId);

                model.ResItemId = Convert.ToInt32(ddlParcelList);
                model.JobsiteId = Convert.ToInt32(JobsiteSeq[1]);
                model.ReqId = Convert.ToInt32(hdReqId);
                model.ItemName = hdItemName;
                model.RequestType = ddlParcelType;

                service.InsertDtl(model, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Details", new { id = model.ReqId });
            }

            return View();

        }

        public ActionResult EditDetails(int id, int WhId)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var itemDtl = service.SelectRequestParcelDtl(new Models.ICM.RequestParcelDtl { ReqDtlId = id, RecordStatus = "!D" }, new[] { "JobSite" }).FirstOrDefault();


            if (itemDtl != null)
            {
                int intReqId = Convert.ToInt32(itemDtl.ReqId);
                int intProjectId = Convert.ToInt32(service.SelectRequestParcel(new Models.ICM.RequestParcel { ReqParcelId = intReqId, RecordStatus = "!D" }, null).FirstOrDefault().ProjectId);
                string strParcelType = itemDtl.RequestType;
                int intResItemId = Convert.ToInt32(itemDtl.ResItemId);

                ViewBag.ReqId = itemDtl.ReqId;
                ViewBag.Unit = service.GetUnitName(strParcelType, intResItemId);
                var allReqQuantity = service.GetQuantity(strParcelType, intResItemId, intProjectId, WhId); 
                ViewBag.Quantity = allReqQuantity + itemDtl.Quantity;

                return View(itemDtl);
            }

            return HttpNotFound();

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditDetails(RequestParcelDtl model)
        {
            try
            {
                if (ModelState.IsValid)
                {

                    var service = new RequestParcelService.RequestParcelServiceClient();
                    var JobsiteSeq = service.GetJobsite(Class.GimsMembership.CurrentEmpId);
                    model.JobsiteId = Convert.ToInt32(JobsiteSeq[1]);

                    service.UpdateDtl(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new { id = model.ReqId });
                }
                return Edit(model.ReqDtlId);
            }
            catch
            {
                return Edit(model.ReqDtlId);
            }
        }

        public ActionResult DeleteDetails(int id, int intReqId)
        {
            try
            {
                var service = new RequestParcelService.RequestParcelServiceClient();
                service.DeleteDtl(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Details", new { id = intReqId });
            }
            catch
            {
                return Index();
            }
        }

        public ActionResult DeleteDtlAll(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new RequestParcelService.RequestParcelServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteDtl(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        #endregion

        #region GetData

        public ActionResult GetParcelSelectList(string strParcelType, int intProjectId, int intWhId)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var Parcel = service.ParcelSelectList(strParcelType, intProjectId, intWhId);
            return this.Json(Parcel, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetQuantity(string strParcelType, int intResItemId, int? intProjectId, int intWhId)
        {
            ViewBag.Item = intResItemId;
            var service = new RequestParcelService.RequestParcelServiceClient();

            string strUnit = service.GetUnitName(strParcelType, intResItemId);
            int intQuantity = service.GetQuantity(strParcelType, intResItemId, intProjectId, intWhId);
             
            return this.Json(new { Quantity = intQuantity, Unit = strUnit }, JsonRequestBehavior.AllowGet);


        }
         
        public ActionResult _ResItemHistory()
        {
            return View();
        }

        #endregion

        #region Send Request For Approved

        public ActionResult Sending(int id)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            service.UpdateRequestForApproved(id, Class.GimsMembership.CurrentEmpId);

            return Json(new { success = true });
            //return RedirectToAction("Index");
        }

        #endregion

        #region Report

        public void ReportPar(int ReqId)
        {
            var service = new RequestParcelService.RequestParcelServiceClient();
            var model = service.SelectRequestParcel(new Models.ICM.RequestParcel { ReqParcelId = ReqId, RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus }, new[] { "Employee", "Employee.Position" }).FirstOrDefault();
            // var model1 = service.SelectRequestParcelDtl(new RequestParcelDtl() { ReqId = ReqId, RecordStatus = "!" + KPIS.GERP.Models.SYS.RecordStatus.DeletedStatus }, null).ToList();

            Dictionary<string, string> fields = new Dictionary<string, string>();
            MailMerge mailMerge = new MailMerge();

            fields.Add("ReqCode", model.IcmReqCode);
            fields.Add("ReqDate", model.WantedDate != null ? model.WantedDate.Value.ToShortDateString() : "");
            fields.Add("CreateBy", model.Employee.FullName);
            fields.Add("CreateWhen", model.CreatedWhen != null ? model.CreatedWhen.Value.ToShortDateString() : "");
            fields.Add("PositionName", model.Employee.Position.Name);

            var dics = service.ReqItem(ReqId).ToList();

            string strTemplatePath = Server.MapPath("~/Templates/ใบเบิกวัสดุ.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("ใบเบิกวัสดุ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, dics, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                if (true)
                {
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                }
                Response.End();
            }
        }
        #endregion
    }
}
